package com.zksk.admin.service.member.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksk.admin.api.domain.portal.vo.ConsultVo;
import com.zksk.admin.domain.member.dto.DistributionDto;
import com.zksk.admin.domain.member.dto.OperatorDto;
import com.zksk.admin.domain.member.dto.MemberDto;
import com.zksk.admin.domain.member.vo.MemberVo;
import com.zksk.admin.mapper.member.MemberDao;
import com.zksk.admin.service.member.MemberService;
import com.zksk.common.core.domain.R;
import com.zksk.common.security.utils.SecurityUtils;
import com.zksk.mbg.admin.domain.*;
import com.zksk.mbg.admin.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 企业管理
 * @author: xiebo
 * @create: 2022-12-15 10:55
 **/
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService
{

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private MemberOperatorMapper memberOperatorMapper;

    @Autowired
    private MemberManageMapper memberManageMapper;

    @Autowired
    private MemberScoreMapper memberScoreMapper;

    @Autowired
    private MemberCredentialMapper memberCredentialMapper;

    @Autowired
    private ConsultMapper consultMapper;

    @Autowired
    private SaleRecordMapper saleRecordMapper;


    /**
     * 新增企业信息
     *
     * @param memberVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R insert(MemberVo memberVo)
    {

        Member member = BeanUtil.copyProperties(memberVo, Member.class);
        member.setMemberId(null);
        if (ObjectUtil.isEmpty(member.getIfSale()))
        {
            //未传是否营销默认为未营销
            member.setIfSale(0);
        }
        if (ObjectUtil.isEmpty(member.getStatus()))
        {
            //未传用户类型设置为未申请用户
            member.setStatus(0);
        }
        //新增企业基本信息
        int insert = memberMapper.insert(member);

        //新增企业经办人
        MemberOperator memberOperator = memberVo.getMemberOperator();
        memberOperator
                //设置主键为null
                .setId(null)
                //绑定企业ID
                .setMemberId(member.getMemberId())
                //设置为默认经办人
                .setDefaultOp(0)
                //设置为存在
                .setDelFlag(0)
                //设置创建人
                .setCreateBy(SecurityUtils.getUsername());
        //新增经办人信息
        memberOperatorMapper.insert(memberOperator);

        if (ObjectUtil.isNotEmpty(memberVo.getMemberManage()))
        {
            //新增企业经营信息
            memberManageMapper.insert(
                    memberVo.getMemberManage()
                            .setId(null)
                            //绑定企业ID
                            .setMemberId(member.getMemberId()));
        }

        if (CollUtil.isNotEmpty(memberVo.getMemberScoreList()))
        {
            this.insertMemberScore(memberVo.getMemberScoreList(), member.getMemberId());
        }

        if (CollUtil.isNotEmpty(memberVo.getMemberCredentialList()))
        {
            this.insertMemberCredential(memberVo.getMemberCredentialList(), member.getMemberId());
        }

        return R.ok("新增" + insert + "条记录", "新增成功!");
    }

    /**
     * 修改企业信息
     *
     * @param memberVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateMember(MemberVo memberVo)
    {

        Member member = BeanUtil.copyProperties(memberVo, Member.class);
        //设置修改人
        member.setUpdateBy(SecurityUtils.getUsername());
        //修改企业基本信息
        int update = memberMapper.updateById(member);

        //修改默认经办人
        this.updateOperator(memberVo.getMemberId(),memberVo.getMemberOperator().getOperatorName(),memberVo.getMemberOperator().getOperatorPhone());

        if (ObjectUtil.isNotEmpty(memberVo.getMemberManage()))
        {

            if (memberVo.getMemberManage().getId() == null || memberVo.getMemberManage().getId().equals(0L))
            {
                throw new RuntimeException("未传经营信息ID!");
            }
            else
            {
                MemberManage memberManage = memberVo.getMemberManage();
                memberManage
                        //设置修改人
                        .setUpdateBy(SecurityUtils.getUsername());
                //修改经营信息
                memberManageMapper.updateById(memberManage);
            }
        }

        if (CollUtil.isNotEmpty(memberVo.getMemberScoreList()))
        {
            this.deleteMemberScore(memberVo.getMemberId());
            this.insertMemberScore(memberVo.getMemberScoreList(), memberVo.getMemberId());
        }

        if (CollUtil.isNotEmpty(memberVo.getMemberCredentialList()))
        {
            this.deleteMemberCredential(memberVo.getMemberId());
            this.insertMemberCredential(memberVo.getMemberCredentialList(), memberVo.getMemberId());
        }

        return R.ok("修改" + update + "条记录", "修改成功!");
    }


    /**
     * 修改默认经办人
     * @param memberId
     * @param operatorName
     * @param operatorPhone
     */
    public void updateOperator(Long memberId,String operatorName,String operatorPhone)
    {
        //根据经办人姓名和手机号码查询有无此经办人
        MemberOperator memberOperator = memberOperatorMapper.selectOne(
                new LambdaQueryWrapper<MemberOperator>()
                        //企业用户ID
                        .eq(MemberOperator::getMemberId, memberId)
                        //经办人姓名
                        .eq(MemberOperator::getOperatorName, operatorName)
                        //经办人手机号码
                        .eq(MemberOperator::getOperatorPhone, operatorPhone)
        );

        //查询默认经办人
        MemberOperator defaultOp = memberOperatorMapper.selectOne(
                new LambdaQueryWrapper<MemberOperator>()
                        //企业用户ID
                        .eq(MemberOperator::getMemberId, memberId)
                        //默认经办人
                        .eq(MemberOperator::getDefaultOp, 0)
        );

        if (BeanUtil.isEmpty(memberOperator))
        {
            MemberOperator memberOperator1 = new MemberOperator();
            //没有该经办人则新增
            memberOperator1
                    //绑定企业ID
                    .setMemberId(memberId)
                    //设置经办人姓名
                    .setOperatorName(operatorName)
                    //设置经办人联系方式
                    .setOperatorPhone(operatorPhone)
                    //设置为默认经办人
                    .setDefaultOp(0)
                    //设置为存在
                    .setDelFlag(0)
                    //设置创建人
                    .setCreateBy(SecurityUtils.getUsername());
            //新增经办人为默认
            memberOperatorMapper.insert(memberOperator1);

            defaultOp
                    .setDefaultOp(2)
                    .setUpdateBy(SecurityUtils.getUsername());
            //修改之前经办人为非默认
            memberOperatorMapper.updateById(defaultOp);
        }
        else
        {
            if (!memberOperator.getId().equals(defaultOp.getId()))
            {
                //存在该经办人且不是当前默认则修改
                memberOperator
                        //设置为默认经办人
                        .setDefaultOp(0)
                        //修改人
                        .setUpdateBy(SecurityUtils.getUsername());
                //修改传入经办人为默认
                memberOperatorMapper.updateById(memberOperator);

                defaultOp
                        .setDefaultOp(2)
                        .setUpdateBy(SecurityUtils.getUsername());
                //修改之前默认经办人为非默认
                memberOperatorMapper.updateById(defaultOp);
            }
        }
    }


    /**
     * 校验手机号
     *
     * @param operatorPhone
     * @return
     */
    @Override
    public boolean checkOperatorPhone(String operatorPhone)
    {

        if (memberOperatorMapper.selectCount(new LambdaQueryWrapper<MemberOperator>().eq(MemberOperator::getOperatorPhone, operatorPhone)) > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 删除企业信息
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteMember(List<Long> ids)
    {

        //因企业信息为重要信息,必须逻辑删除,因此其他数据暂留,如需变动打开注释
//        ids.forEach(id ->
//        {
//            //查询企业经办人信息
//            List<MemberOperator> memberOperators = memberOperatorMapper.selectList(
//                    new LambdaQueryWrapper<MemberOperator>()
//                            .eq(MemberOperator::getMemberId, id)
//            );
//            //删除企业经办人
//            memberOperatorMapper.deleteBatchIds(memberOperators.stream().map(MemberOperator::getId).collect(Collectors.toList()));
//            //查询用户经营信息
//            List<MemberManage> memberManages = memberManageMapper.selectList(
//                    new LambdaQueryWrapper<MemberManage>()
//                            .eq(MemberManage::getMemberId, id)
//            );
//            //删除用户经营信息
//            memberManageMapper.deleteBatchIds(memberManages.stream().map(MemberManage::getId).collect(Collectors.toList()));
//
//            //删除过往业绩
//            this.deleteMemberScore(id);
//
//            //删除资质证书
//            this.deleteMemberCredential(id);
//
//        });

        int i = memberMapper.deleteBatchIds(ids);

        return R.ok("共删除:" + i + "条数据!", "删除成功!");
    }

    /**
     * 根据ID查询企业信息
     *
     * @param id
     * @return
     */
    @Override
    public R<MemberVo> selectById(Long id)
    {

        MemberVo memberVo = new MemberVo();

        //查询企业基础信息
        Member member = memberMapper.selectById(id);
        BeanUtil.copyProperties(member, memberVo);

        //查询企业经办人信息
        List<MemberOperator> memberOperators = memberOperatorMapper.selectList(
                new LambdaQueryWrapper<MemberOperator>()
                        .eq(MemberOperator::getMemberId, id));
        MemberOperator memberOperator = memberOperators.stream()
                .filter(item -> item.getDefaultOp().equals(0))
                .findAny()
                .orElse(null);

        //查询企业经营信息
        MemberManage memberManage = memberManageMapper.selectOne(
                new LambdaQueryWrapper<MemberManage>()
                        .eq(MemberManage::getMemberId, id)
        );

        //查询该企业的所有过往业绩
        List<MemberScore> memberScores = memberScoreMapper.selectList(
                new LambdaQueryWrapper<MemberScore>().eq(MemberScore::getMemberId, id));

        //查询该企业的所有资质证书
        List<MemberCredential> memberCredentials = memberCredentialMapper.selectList(
                new LambdaQueryWrapper<MemberCredential>().eq(MemberCredential::getMemberId, id));

        //查询企业产品咨询信息
        List<Consult> consults = consultMapper.selectList(
                new LambdaQueryWrapper<Consult>()
                        .eq(Consult::getMemberId, id)
                        .orderByAsc(Consult::getCreateTime)
        );

        memberVo
                .setMemberOperator(memberOperator)
                .setMemberManage(memberManage)
                .setMemberScoreList(memberScores)
                .setMemberCredentialList(memberCredentials)
                .setConsultVoList(BeanUtil.copyToList(consults, ConsultVo.class));

        return R.ok(memberVo, "查询成功!");
    }

    /**
     * 分页条件查询企业信息
     *
     * @param memberDto
     * @return
     */
    @Override
    public R<Page<MemberVo>> selectList(MemberDto memberDto)
    {

        Page<MemberVo> memberPage = memberDao.selectPageList
                (
                        //分页
                        new Page<>(memberDto.getPageNum(), memberDto.getPageSize()),
                        //条件筛选
                        new QueryWrapper<Member>()
                                //企业名称
                                .like(StrUtil.isNotEmpty(memberDto.getMemberName()), "m.member_name", memberDto.getMemberName())
                                //企业等级
                                .like(StrUtil.isNotEmpty(memberDto.getMemberLevel()), "m.member_level", memberDto.getMemberLevel())
                                //所属平台
                                .like(StrUtil.isNotEmpty(memberDto.getStationsName()), "m.stations_name", memberDto.getStationsName())
                                //是否营销
                                .eq(ObjectUtil.isNotEmpty(memberDto.getIfSale()), "m.if_sale", memberDto.getIfSale())
                                //营销人员名称
                                .like(StrUtil.isNotEmpty(memberDto.getSaleUsername()), "m.sale_username", memberDto.getSaleUsername())
                                //用户类型
                                .eq(ObjectUtil.isNotEmpty(memberDto.getStatus()), "m.status", memberDto.getStatus())
                );
        return R.ok(memberPage, "查询成功!");
    }

    /**
     * 分配营销人员
     *
     * @param distributionDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R distribution(DistributionDto distributionDto)
    {

        //查询企业咨询记录
        List<Consult> consults = consultMapper.selectList(
                new LambdaQueryWrapper<Consult>()
                        .in(Consult::getMemberId, distributionDto.getIds())
        );

        distributionDto.getIds().forEach(id ->
        {
            //获取当前企业的咨询记录
            List<Consult> collect = consults.stream().filter(item -> item.getMemberId().equals(id)).collect(Collectors.toList());

            //当前企业存在咨询记录,新增营销记录
            if (CollUtil.isNotEmpty(collect))
            {
                consults.forEach(item ->
                {
                    SaleRecord saleRecord = new SaleRecord();
                    saleRecord
                            .setId(null)
                            .setMemberId(id)
                            .setUserId(distributionDto.getSaleUser())
                            .setEnumProductId(item.getProductEnumId())
                            .setEnumProductName(item.getProductEnumName())
                            .setIntention(item.getDesc());
                    //新增营销记录
                    saleRecordMapper.insert(saleRecord);
                });

            }
            //分配营销
            memberDao.distribution(id, distributionDto.getSaleUser(), distributionDto.getSaleUsername(), DateUtil.toLocalDateTime(DateUtil.date()));
        });
        return R.ok("分配完成!");
    }

    /**
     * 校验企业名称
     *
     * @param memberName
     * @return
     */
    @Override
    public boolean checkMemberName(String memberName)
    {
        if (memberMapper.selectCount(new LambdaQueryWrapper<Member>().eq(Member::getMemberName, memberName)) > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    @Override
    public boolean checkCreditCode(String creditCode)
    {
        if (memberMapper.selectCount(new LambdaQueryWrapper<Member>().eq(Member::getCreditCode, creditCode)) > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 查询历史经办人
     *
     * @param operatorDto
     * @return
     */
    @Override
    public R<Page<MemberOperator>> getManageList(OperatorDto operatorDto)
    {
        Page<MemberOperator> memberManagePage = memberOperatorMapper.selectPage(
                new Page<>(operatorDto.getPageNum(), operatorDto.getPageSize()),
                new LambdaQueryWrapper<MemberOperator>()
                        .eq(MemberOperator::getMemberId, operatorDto.getMemberId())
                        .orderByDesc(MemberOperator::getCreateTime)
        );
        return R.ok(memberManagePage, "查询成功！");
    }

    /**
     * 删除经办人信息
     * @param ids
     * @return
     */
    @Override
    public R deleteOperator(List<Long> ids)
    {
        List<MemberOperator> memberOperators = memberOperatorMapper.selectBatchIds(ids);
        List<MemberOperator> collect = memberOperators.stream().filter(item -> item.getDefaultOp().equals(0)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect))
        {
            return R.fail("不能删除默认经办人！");
        }
        else
        {
            return R.ok("共删除" + memberOperatorMapper.deleteBatchIds(ids) + "条记录！","删除成功！");
        }
    }

    /**
     * 新增企业过往业绩
     *
     * @param memberScoreList
     */
    private void insertMemberScore(List<MemberScore> memberScoreList, Long memberId)
    {
        memberScoreList.forEach(item ->
        {
            item
                    //设置主键为null
                    .setId(null)
                    //绑定企业ID
                    .setMemberId(memberId)
                    //设置为存在
                    .setDelFlag(0)
                    //设置创建人
                    .setCreateBy(SecurityUtils.getUsername());
            //新增业绩
            memberScoreMapper.insert(item);
        });
    }

    /**
     * 新增企业资质证书
     *
     * @param memberCredentialList
     */
    private void insertMemberCredential(List<MemberCredential> memberCredentialList, Long memberId)
    {
        memberCredentialList.forEach(item ->
        {
            item
                    //设置主键为null
                    .setId(null)
                    //绑定企业ID
                    .setMemberId(memberId)
                    //设置为存在
                    .setDelFlag(0)
                    //设置创建人
                    .setCreateBy(SecurityUtils.getUsername());
            //新增资质证书
            memberCredentialMapper.insert(item);
        });
    }

    /**
     * 删除企业过往业绩
     */
    private void deleteMemberScore(Long memberId)
    {
        //查询该企业的所有过往业绩
        List<MemberScore> memberScores = memberScoreMapper.selectList(
                new LambdaQueryWrapper<MemberScore>().eq(MemberScore::getMemberId, memberId));

        //获取所有需要删除的ID集合
        List<Long> collect = memberScores.stream()
                .map(MemberScore::getId)
                .collect(Collectors.toList());
        //删除该企业的所有过往业绩
        memberScoreMapper.deleteBatchIds(collect);
    }

    /**
     * 删除企业资质证书
     *
     * @param memberId
     */
    private void deleteMemberCredential(Long memberId)
    {

        //查询该企业的所有资质证书
        List<MemberCredential> memberCredentials = memberCredentialMapper.selectList(
                new LambdaQueryWrapper<MemberCredential>().eq(MemberCredential::getMemberId, memberId));
        //获取所有需要删除的ID集合
        List<Long> collect = memberCredentials.stream()
                .map(MemberCredential::getId)
                .collect(Collectors.toList());
        //删除该企业的所有企业资质证书
        memberCredentialMapper.deleteBatchIds(collect);
    }


}
